package com.yunc.base.utils;

import com.yunc.modules.sys.entity.SysLoginLog;
import com.yunc.modules.sys.service.ISysLoginLogService;
import eu.bitwalker.useragentutils.UserAgent;
import org.apache.commons.lang3.StringUtils;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;

/**
 * 登录日志
 *
 * @author taocongcong
 * @create 2020-03-10 10:09
 */
public class LoginLogUtils {

    public static void loginLog(final HttpServletRequest request, String message, String status) {
        ThreadPoolTaskExecutor taskExecutor = (ThreadPoolTaskExecutor)SpringContextUtils.getBean("taskExecutor");
        ISysLoginLogService sysLoginLogService = (ISysLoginLogService)SpringContextUtils.getBean("sysLoginLogService");
        final UserAgent userAgent = UserAgent.parseUserAgentString(request.getHeader("User-Agent"));
        final String ip = IPUtils.getIpAddr(request);
        String loginName = getRequestParameter(request, "loginName");
        taskExecutor.execute(() -> {
            // 获取客户端操作系统
            String os = userAgent.getOperatingSystem().getName();
            // 获取客户端浏览器
            String browser = userAgent.getBrowser().getName();
            SysLoginLog loginLog = new SysLoginLog();
            loginLog.setLoginName(loginName);
            loginLog.setOs(os);
            loginLog.setBrowser(browser);
            String location = IPUtils.getCityInfo(ip);
            loginLog.setIpAddress(ip);
            loginLog.setLoginLocation(location);
            loginLog.setLoginTime(new Date());
            loginLog.setStatus(status);
            loginLog.setMsg(message);
            sysLoginLogService.save(loginLog);
        });
    }

    public static String getRequestParameter(HttpServletRequest httpRequest, String parameter){
        String requestParameter = httpRequest.getHeader(parameter);
        if (StringUtils.isBlank(requestParameter)) {
            requestParameter = httpRequest.getParameter(parameter);
        }
        return requestParameter;
    }

}
